package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-21 14:46:41
 * @Description : 二叉树求每层最大的值
 * @Version : 1.0
 */
public class Code515Test {

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new java.util.LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node == null) {
                    continue;
                }
                max = Math.max(max, node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(max);
        }

        return res;
    }

    @Test
    public void test1() {
        TreeNode root = new TreeNode(1);
        TreeNode node3 = new TreeNode(3);
        TreeNode node2 = new TreeNode(2);
        root.left = node3;
        root.right = node2;

        node3.left = new TreeNode(5);
        node3.right = new TreeNode(3);

        node2.right = new TreeNode(9);

        assert largestValues(root).equals(Arrays.asList(1, 3, 9));
    }

    @Test
    public void test2() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        assert largestValues(root).equals(Arrays.asList(1, 3));
    }
}
